require([
    'formax/common'
], function() {

    var $assignModal = $('#customer-assign-modal'),
        $checkedCustomers = $('#search-result [name^=customers]'),
        $followModal = $('#customer-follow-modal');

    // 分配客户对话框
    if ($assignModal.length) {
        $assignModal.on('show.bs.modal', function(options) {
            if ($(options.relatedTarget).is('button') && $checkedCustomers.checkedValues().length === 0) {
                dialog.error(__('Checked customers is required'));
                return false;
            }
            return true;
        }).on('shown.bs.modal', function() {
            var $warp = $('form[name=customer-assign] .modal-body', $assignModal);
            $.each($checkedCustomers.checkedValues(), function(i, n) {
                $warp.prepend('<input type="hidden" name="customers[]" value="' + n + '" />');
            });

            // 创建新的批次
            var $assign_id = $warp.find('[name=assign_id]');
            $warp.find('#create-new-batch').click(function(e) {
                e.preventDefault();
                bootbox.prompt({
                    title: __('New assign batch') + ':',
                    value: $(this).data('value'),
                    callback: function(result) {
                        if ($.trim(result).length) {
                            $.post(
                                FORMAX.baseUrl + 'customer/new-assign', {
                                    name: $.trim(result)
                                }, function(json) {
                                    if (json.code !== 200) {
                                        return dialog.error(json.message);
                                    }
                                    $assign_id.prepend($('<option>', {
                                        value: json.data.assign_id,
                                        text: result
                                    }));
                                    $assign_id.val(json.data.assign_id).trigger('change');
                                }, 'json'
                            );
                        }
                    }
                });
            });

            // 销售人员选择
            $warp.find('[name=sales_user_id]').change(function() {
                var parent_id = $(this).find('option:selected').data('parent-id');
                if (parent_id) {
                    $warp.find('[name=manager_user_id]').val(parent_id).trigger('change');
                }
            });
        });
    }

    // 跟进客户对话框
    if ($followModal.length) {
    }
});
